package engine.display.newAttack
{
	import engine.display.newAttack.vo.DamageVo;
	import engine.display.newAttack.vo.FightInfoVo;
	import engine.flag.PlayerActionFlag;
	import engine.logic.McPool;
	import engine.scene.player.MoveAction;
	
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.text.TextField;
	import flash.utils.setTimeout;
	
	import newx.StageInfo;
	import newx.com.ResManager;
	import newx.com.config.StaticIni;
	import newx.com.control.text.NxLabel;
	import newx.com.loader.SwfLoader;

	/**
	 * 玩家对象
	 * @author lw
	 * 
	 */	
	public class AttackPlayer extends Sprite
	{
		private var _fightInfoVo		:FightInfoVo;
		
		private var _initX				:int;
		
		private var _initY				:int;
		
		private var _pos				:int;
		
		//头顶的点
		private var _overheadPoint		:Point;
		
		//人物中心点
		private var _chestPoint		:Point;
		
		//脚下的点
		private var _originPoint		:Point;
		
		//受伤点
		private var _ePosPoint			:Point;
		
		//攻击点
		private var _sPosPoint			:Point;
		
		private var _pInfoUI			:MovieClip;
		//hp血条长度
		private var _bar1Width			:uint;
		//mp气势条长度
		private var _bar2Width			:uint;
		
		/**角色动画*/
		private var _actionMovie		:MovieClip;
		
		//默认形象
		private var _defaultMovie		:MovieClip;
		
		//当前动作
		private var _actId				:int;
		
		private var _npcscaleX			:int;
		
		private var _actFuncs			:Array;
		
		private var _bufferList		:Array;
		
		private var _playerPlace		:Sprite;
		
		private var _effectPlace		:Sprite;
		
		private var _bufferPlace		:Sprite;;
		
		private var _spPlace			:Sprite;
		
		private var _spEffect			:MovieClip;
		
		private var _taskPlace			:MovieClip;
		
		private var _taskTxt			:TextField;
		
		
		
		public function AttackPlayer( pos : int )
		{
			_pos				=	pos;
			_actFuncs		= [ playerAwait, playerRunOut, playerRunBack, 
				playerAttack, playerLongAttack, playerMagic, playerMagicAttack, 
				playerDefend, null, playerBeAttack, playerdeath, playerBeMiss,playerDelight ];
			if(! (this is AttackPet))
			{
				init();
			}
		}
		
		private function init():void
		{
			_bufferList		= [];
			
			_defaultMovie 	=  ResManager.newResClass( "custSkin_86" ) as MovieClip;
			
			//放入显示玩家血，名字，等级的mc
			_pInfoUI		=	ResManager.newResClass("npcbox") as MovieClip;//ResManager.getResContentCopy("npcbox") as MovieClip;
			_bar1Width		=	_pInfoUI.bar1.masker.width;
			_bar2Width		=	_pInfoUI.bar1.masker.width;
			_pInfoUI.mouseChildren = _pInfoUI.mouseEnabled = false;
			addChild(_pInfoUI);
			
			_playerPlace	=	new Sprite();
			_pInfoUI.npcSpace.addChild( _playerPlace );
			
			_bufferPlace	=	new Sprite();
			_pInfoUI.addChild( _bufferPlace );
			
			_effectPlace	=	new Sprite();
			addChild( _effectPlace );
			
			_spPlace		=	new Sprite();
			_pInfoUI.npcSpace.addChild( _spPlace );
			_spPlace.alpha		=	.8
//			_spPlace.addChild( _spEffect );
			_spPlace.mouseChildren = _spPlace.mouseEnabled = _spPlace.visible = false;
			
			_taskTxt 		=	new TextField();
			addChild( _taskTxt );
			_taskTxt.wordWrap  = true;
			_taskTxt.mouseEnabled = false;
			
			_npcscaleX 		=  _pos > 9 ? -1 : 1;
			
			_initX 			= uint(StaticIni.getIniVar(String(_pos),"x"));
			_initY			= uint(StaticIni.getIniVar(String(_pos),"y"));
			
			reSetView();
			
			visible = mouseChildren = false;
			
			this.buttonMode = true;
			
			addEventListener( MouseEvent.MOUSE_OVER, onOver );
			addEventListener( MouseEvent.MOUSE_OUT, onOut );
		}
		
		public function speak( content : String ):void
		{
			if( content == "" )
			{
				_taskTxt.htmlText = "";
				
				if( _taskPlace !=null && _taskPlace.visible  )
				{
//					_taskPlace.parent.removeChild( _taskPlace );
					_taskPlace.visible=false;
				}
				return;
			}
			
			if( null == _taskPlace )
			{
				_taskPlace = ResManager.newResClass( "CustomControl_023" ) as MovieClip;
				_taskPlace.mouseChildren = _taskPlace.mouseEnabled = false;
				addChild( _taskPlace );
			}
			_taskPlace.visible=true;
			_taskTxt.htmlText = StaticIni.getSwfLangStr( content );
			_taskTxt.filters = [ NxLabel.glow ];
			_taskTxt.y = overheadPoint.y - _taskTxt.textHeight;
			_taskTxt.x = overheadPoint.x - _taskTxt.textWidth * .5;
			addChild( _taskTxt );
			
			_taskPlace.x = _taskTxt.x - 8;
			_taskPlace.y = _taskTxt.y - 8;
			
			_taskPlace.width = _taskTxt.textWidth + 20;
			_taskPlace.height = _taskTxt.textHeight + 30;
		}
		
		private function onOver( evt : MouseEvent ):void
		{
			if( x != _initX && y != _initY )
			{
				return;
			}
			if( _fightInfoVo != null && _fightInfoVo.dead != 1)
			{
				AttackTipsLogic.getInstance().showTips( _fightInfoVo );
				
				if( !hasEventListener( MouseEvent.MOUSE_MOVE ) ) 
				{
					addEventListener( MouseEvent.MOUSE_MOVE, onMove );
				}
			}
		}
		
		private function onOut( evt : MouseEvent ):void
		{
			removeEventListener( MouseEvent.MOUSE_MOVE, onMove );
			
			AttackTipsLogic.getInstance().hideTips();
		}
		
		private function onMove( evt : MouseEvent ):void
		{
			AttackTipsLogic.getInstance().moveTo( evt.stageX, evt.stageY );
		}
		
		//初始化位置
		public function reSetView():void
		{
			x	=	_initX;
			y	=	_initY;
			
			_pInfoUI.npcSpace.scaleX = _npcscaleX;
		}
		
		/**
		 *	复位,出战斗的时候，全部复位 
		 * 
		 */		
		public function reset():void
		{
			if( null != _actionMovie )
			{
				_actionMovie.stop();
				
				if( null != _actionMovie.parent)
				{
					_actionMovie.parent.removeChild( _actionMovie );
				}
				
				_actionMovie = null;
			}
			
			clearMC( _bufferPlace );
			clearMC( _effectPlace );
			clearMC( _playerPlace );
			
			fightInfoVo = null;
			
			_pInfoUI.visible = false;
			
			_spPlace.mouseChildren = _spPlace.mouseEnabled = _spPlace.visible = this.buttonMode = false;
	
			_actId = 0;
			
			showBuffer("");
		}
		
		private function clearMC( place : DisplayObjectContainer ):void
		{
			var mc : MovieClip;
			while( place.numChildren > 0 )
			{
				mc = place.getChildAt( 0 ) as MovieClip;
				place.removeChild( mc );
				
				McPool.returnRes( mc[ "url" ], mc );
			}
		}
		
		//设置要放入的对象,并设置加载完成后的回调
		public function set fightInfoVo( val : FightInfoVo ):void
		{
			_fightInfoVo	=	val;
			
			if( null == _fightInfoVo ) return;
			
			_pInfoUI.nameField.htmlText	=	_fightInfoVo.name;
			
			_pInfoUI.levelField.text	=	_fightInfoVo.lv;
			var titleName:String = StaticIni.getSwfLangStr("TitleName_"+_fightInfoVo.realconfigID);
			if(titleName != "TitleName_" + _fightInfoVo.realconfigID)
			{
				_pInfoUI.titleField.htmlText = titleName;
			}else
			{
				_pInfoUI.titleField.htmlText = "";
			}
			
			updataHP();
			updataMP();
			
			
//			IO.traceError("fightInfoVo = " + _fightInfoVo.name);
			onActionMovieLoaded();
		}
		
		public function get fightInfoVo():FightInfoVo
		{
			return _fightInfoVo;
		}
		
		private function updataHP():void
		{
			if( _fightInfoVo.hp <= 0 )
			{
				_pInfoUI.bar1.masker.width =	0;
			}
			else
			{
				_pInfoUI.bar1.masker.width =	_bar1Width * ( _fightInfoVo.hp / _fightInfoVo.maxHp );
			}
		}
		
		private function updataMP():void
		{
			if( _fightInfoVo.maxMp <= 0 )
			{
				_pInfoUI.bar2.masker.width =	0;
			}
			else
			{
				_pInfoUI.bar2.masker.width =	_bar2Width * ( _fightInfoVo.mp / _fightInfoVo.maxMp );
			}
			
			if( null == _spEffect )
			{
				_spEffect		=	ResManager.newResClass("effect_7300141") as MovieClip;
			}
			
			_spPlace.mouseChildren = _spPlace.mouseEnabled = _spPlace.visible = !( _fightInfoVo.hp == 0 || _fightInfoVo.mp < 100 );
			
			this.buttonMode =  _fightInfoVo.dead != 1 ;
			
			if( null == _spEffect )
			{
				return;
			}
			_spPlace.addChild( _spEffect );
			
			if( _spPlace.visible )
			{
				_spPlace.x = originPoint.x;
				_spPlace.y = originPoint.y;
				( _spEffect.movie as MovieClip ).play();
				
			}else
			{
				( _spEffect.movie as MovieClip ).stop();
			}
		}
		
		/**
		 *	获取模型url 
		 */
		private function getModelUrl():String	
		{
			if( 2 == _fightInfoVo.type )
			{
				return StageInfo.npcResPath + "npc_"+_fightInfoVo.configID + "_" + _fightInfoVo.clothemodel + ".swf";
//				return StageInfo.npcResPath + "fight_role_22012200_1.swf";
			}else
			{
				return StageInfo.npcResPath + "npc_"+_fightInfoVo.configID + ".swf";
			}
		}
		
		public	function getSkin():MovieClip
		{
			return _actionMovie;
		}
		
		private function onActionMovieLoaded():void
		{
			_actionMovie = _defaultMovie;
			
			_playerPlace.addChild( _actionMovie );
			
			updataPoint( _actionMovie );
			
			var skinUrl : String = getModelUrl();
			
			//加载真实对象，
			SwfLoader.StartLoad( skinUrl, null, function( mc : DisplayObject, pList : Array ):void
			{
				if( null == mc ) return;
				
				
				_actionMovie = mc as MovieClip;
//				IO.traceError( _actionMovie.numChildren + "-------------------1" + skinUrl);
				if(_actionMovie.numChildren == 1 && _actionMovie.totalFrames == 1 )
				{
					_actionMovie = _actionMovie.getChildAt( 0 ) as MovieClip;
				}else
				{
					_actionMovie = ResManager.copy( _actionMovie ) as  MovieClip;
				}
				
//				IO.traceError( _actionMovie.numChildren + "-------------------2");
				
				while( _playerPlace.numChildren > 0 )
				{
					_playerPlace.removeChildAt( 0 );
				}
				
				_playerPlace.addChild( _actionMovie );
				
				updataPoint( _actionMovie );
				
				if( null != _defaultMovie.parent )
				{
					_defaultMovie.parent.removeChild( _defaultMovie );
				}
				
				playToTarget( _actId );
				
			}, null);
			
			_pInfoUI.visible = true;
		}
		
		//添加玩家
		private function addPlayerMovie( playerMovie : MovieClip ):void
		{
			
		}
		
		private function updataPoint( mc : MovieClip ):void
		{
			try
			{
				_overheadPoint = new Point( mc.overhead.x, mc.overhead.y );
				_chestPoint = new Point( mc.chest.x, mc.chest.y );
				_originPoint = new Point( mc.origin.x, mc.origin.y );
				_ePosPoint = new Point( mc.ePos.x, mc.ePos.y );
				_sPosPoint = new Point( mc.sPos.x, mc.sPos.y );
				
				if( mc != _defaultMovie )
				{
					mc.removeChild( mc.overhead );
					mc.removeChild( mc.chest );
					mc.removeChild( mc.origin );
					mc.removeChild( mc.ePos );
					mc.removeChild( mc.sPos );
				}
			} 
			catch(error:Error) 
			{
			}
		}
				
		public	function get pos():int
		{
			return _pos;
		}	
		
		public	function get team():int
		{
			return _pos > 9 ? 1 : 0;
		}	
		
		public	function set dead( dead : int ):void
		{
			_fightInfoVo.dead = dead;
			
			if( dead )
			{
				playToTarget( 10 );
//				_pInfoUI.visible = false;
			}else
			{
				playToTarget( 0 );
//				_pInfoUI.visible = true;
			}
		}	
		
		public	function get dead():int
		{
			return _fightInfoVo.dead;
		}	
		
		public	function playToTarget(actId:int,...argc):void
		{
			_actId			=	actId;
			
			if(this is AttackPet)
			{
				var attackPet:AttackPet = this as AttackPet;
				_actionMovie = attackPet._movie;
				_actId		=	12;
			}
			if( _actionMovie == null )
			{
				return;
			}
			
			var func : Function = _actFuncs[ _actId ];
			
			if( null != func )
			{
				func();
			}
		}
		
		/**	0、原地待机*/
		private function playerAwait():void
		{			
			_actionMovie.scaleX	=	1;
			playMc( PlayerActionFlag.Wait );
		}
		
		/**	1、跑动（->）*/
		private function playerRunOut():void
		{
			_actionMovie.scaleX	=	_npcscaleX;
			playMc( PlayerActionFlag.Run );
		}
		
		/**	2、跑动（<-）*/
		private function playerRunBack():void
		{
			_actionMovie.scaleX	=	-_npcscaleX;
			playMc( PlayerActionFlag.Run );
		}
		
		/**	3、播放物理攻击*/
		private function playerAttack():void
		{
			playMc( PlayerActionFlag.Normal );
		}
		
		/**	4、播放物理攻击（远程）*/
		private function playerLongAttack():void
		{
			playMc("远程攻击开始");
		}
		
		/**	5、法术攻击开始（吟唱）*/
		private function playerMagic():void
		{
			playMc( PlayerActionFlag.Magic );
		}
		
		/**	6、法术攻击发射*/
		private function playerMagicAttack():void
		{			
			playMc( PlayerActionFlag.MagicAttack );
		}
		
		/**	7、防御*/
		private function playerDefend():void
		{
			playMc( PlayerActionFlag.Defend );
		}
		
		/**	9、受伤*/
		private function playerBeAttack():void
		{
			playMc( PlayerActionFlag.Bruise );
		}
		
		/**	10、死亡*/
		private function playerdeath():void
		{
			playMc( PlayerActionFlag.Dead );
		}
		
		/**	11、闪避*/
		private function playerBeMiss():void
		{
			playMc( PlayerActionFlag.Defend );
		}
		
		/**12\宠物高兴开始***/
		private function playerDelight():void
		{
			playMc( PlayerActionFlag.Delight );
		}
		
		private function playMc( frameName : String ):void
		{
			try
			{
				_actionMovie.gotoAndPlay( frameName );
			}catch(e:Error)
			{
				trace(e.message);
			};
		}
		
		/**
		 * @param type		血/内力
		 * @param result	伤害类型
		 * @param val		值
		 */
		public function damage( damageVo : DamageVo ):void
		{
			resetHp( damageVo.hp, damageVo.maxhp );
			
			resetMp( damageVo.mp )
			
			ShowDamage( damageVo.result, damageVo.damageHp, damageVo.damageMp, damageVo.bufferhp );
			
			showBuffer( damageVo.buffer );
	
			if( 1 == damageVo.dead )
			{
				dead = damageVo.dead;
				
				setTimeout( function():void{ _pInfoUI.visible = false;}, 1000 );
			}else if( 0 < damageVo.damageHp )
			{
				playToTarget( 9 );
			}else if( 0 == damageVo.damageHp )
			{
				if(damageVo.buffer!="")
				{
					playToTarget( 0 );
				}else
				{
					playToTarget( 11 );
				}
			}
		}
		
		public function buffHp( hp : int ):void
		{
			ShowDamage( 1, hp, 0, 0 );
		}
		
		public function buffMp( mp : int ):void
		{
			ShowDamage( 1, 0, mp, 0 );
		}
		
		public function resetHp( hp : int, maxhp : int ):void
		{
			_fightInfoVo.hp = hp;
			_fightInfoVo.maxHp = maxhp;
			
			updataHP();
		}
		
		public function resetMp( mp : int ):void
		{
			if(!_fightInfoVo)return;
			if( _fightInfoVo.mp == mp ) return;
			
			_fightInfoVo.mp = mp;
			
			updataMP();
		}
		
		/**
		 *	跳字 
		 * @param result	伤害类型
		 * @param val		值
		 * 
		 */
		public	function ShowDamage( result : int, hp : int, mp : int, bufferdamage : int  ):void
		{
			if ( null == _actionMovie )
			{
				return;
			}
			
			var dx:Number = x	+	_actionMovie.chest.x;
			var dy:Number = y	+	_actionMovie.chest.y + 20;//20是便宜量
			
			//<!-- 1,普通攻击;2,暴击;3,招架4,格挡;5,闪避; -->
			if( 5 != result )
			{//不是闪避
				if( 0 != hp )
				{//跳具体伤害(hp)
					ShowAttackDamage.ShowDamageEffect( ShowAttackDamage.HP, result, hp, new Point( dx, dy ) );
				}
				if( 0 != mp )
				{//mp
					ShowAttackDamage.ShowDamageEffect( ShowAttackDamage.MP, result, mp, new Point( dx, dy ) );
				}
				if( 0 != bufferdamage )
				{//buff伤害
					ShowAttackDamage.ShowDamageEffect( ShowAttackDamage.BUFFERDAMAGE, result, bufferdamage, new Point( dx, dy+30 ) );
				}
			}
			
			if( 1 != result && 0 != result )
			{//普通攻击不跳字
				ShowAttackDamage.ShowTextEffect( result, new Point( dx, dy ) );
			}
		}
		
		/**
		 *	显示buff 
		 * @param buffer
		 * 
		 */
		public function showBuffer( buffer : String = "" ):void
		{
			if( "" != buffer )
			{
				var newBufferList : Array = buffer.split( ";" );
				
				var dx:Number = x	+	chestPoint.x;
				var dy:Number = y	+	chestPoint.y + 80;//80是便宜量
				
				for( var i : int = 0; i < newBufferList.length; i++ )
				{
					newBufferList[ i ] = ( newBufferList[ i ] as String ).split( ":" );
					
					var has : Boolean;
					for( var j : int = 0; j < _bufferList.length; j++ )
					{
						if( newBufferList[ i ][ 0 ] == _bufferList[ j ][ 0 ] )
						{
							has = true;
							break;
						}
					}
					if( !has || int( newBufferList[ i ][ 1 ] ) != int( newBufferList[ i ][ 1 ] ) )
					{//新特效，弹文字跳字
						var buffObj : Object = StaticIni.getIniObj( newBufferList[ i ][ 0 ] ); 
						
						if( null != buffObj )
						{
							ShowAttackDamage.ShowBuffEffect( buffObj.Des, 10, new Point( dx, dy ) );
						}
					}
				}
				
				_bufferList = newBufferList;
			}else
			{
				_bufferList = [];
			}
			
//			showBufferLabel( buffer );
			
			showBufferEffect();
		}
		/**
		 *这nm是在 干嘛
		 *  我猜这个是在做正向查找 和反向查找  匹配当前显示的buff和需要显示的buff
		 * 
		 */		
		private function showBufferEffect():void
		{
			var mc : MovieClip;
			var has : Boolean;
			for(var i : int = 0; i < _bufferPlace.numChildren; i++)
			{
				has = false;
				mc = _bufferPlace.getChildAt( i ) as MovieClip;
				for( var j : int = 0; j < _bufferList.length; j++ )
				{
					if( mc[ "url" ] == _bufferList[ j ] )
					{
						has = true;
						break;
					}
				}
				
				if( !has )
				{
					mc = _bufferPlace.removeChildAt( i ) as MovieClip;
					McPool.returnRes( mc[ "url" ], mc );
					i--;
				}
			}
			
			for( var m : int = 0; m < _bufferList.length; m++ )
			{
				has = false;
				for(var n : int = 0; n < _bufferPlace.numChildren; n++ )
				{
					mc = _bufferPlace.getChildAt( n ) as MovieClip;
					
					if( _bufferList[ m ] == mc[ "url" ] )
					{
						has = true;
						break;
					}
				}
				if( !has )
				{
					var bufferObj : Object = StaticIni.getIniObj( _bufferList[ m ][ 0 ] );//_bufferList[ m ][ 0 ]
					
					if( null != bufferObj )
					{
						mc = McPool.borrowRes( bufferObj.skin );
						
						if( null == mc )
						{//没资源
							continue;
						}
						var pos : String = bufferObj[ "skinpos" ];
						if( null == pos ) pos = "ePos";
						var posPoint : Point = this[ pos + "Point"];
						mc.x = posPoint.x;
						mc.y = posPoint.y;
						mc.scaleX = _npcscaleX;
						_bufferPlace.addChild( mc );//_bufferList[ m ][ 0 ]
						mc.movie.play();
					}
				}
			}
		}
		
		public function showBufferLabel( buffer : String = ""):void
		{
			while( _bufferPlace.numChildren > 0 )
			{
				_bufferPlace.removeChildAt( 0 );
			}
			
			if( "" != buffer )
			{
//				var bufferList : Array = buffer.split( ";" );
//				
//				var mc : MovieClip;
//				for( var i : int = 0; i < bufferList.length; i++ )
//				{
//					bufferList[ i ] = buffer.split( ":" );
//					
//					mc = McPool.borrowRes( "effect_7300103" );
//					mc["url"] = "effect_7";
//					_bufferPlace.addChild( mc );
//				}
				var buff : Array = buffer.split( ":" );
				var txt : NxLabel = new NxLabel();
				txt.htmlText = StaticIni.getSwfLangStr( "BufferDes_" + buff[ 0 ] );
				_bufferPlace.addChild( txt );
				
				_bufferPlace.x = - txt.width * .5;
				_bufferPlace.y = _chestPoint.y - txt.height;
			}
		}

		public function get initX():int
		{
			return _initX;
		}

		public function get initY():int
		{
			return _initY;
		}

		public function get ePosPoint():Point
		{
			if( null == _ePosPoint )
			{
				return new Point( 0, 0 );
			}
			return _ePosPoint;
		}

		public function get originPoint():Point
		{
			if( null == _originPoint )
			{
				return new Point( 0, 0 );
			}
			return _originPoint;
		}

		public function get effectPlace():Sprite
		{
			return _effectPlace;
		}

		public function get overheadPoint():Point
		{
			if( null == _overheadPoint )
			{
				return new Point( 0, 0 );
			}
			return _overheadPoint;
		}

		public function get chestPoint():Point
		{
			if( null == _chestPoint )
			{
				return new Point( 0, 0 );
			}
			return _chestPoint;
		}

		public function get sPosPoint():Point
		{
			if( null == _chestPoint )
			{
				return new Point( 0, 0 );
			}
			return _sPosPoint;
		}
		override public function toString():String
		{
			return super.toString()+"	_pInfoUI?"+_pInfoUI["titleField"].text+"\t"+_pInfoUI["nameField"].text+"	_bufferList?"+_bufferList;
		}
	}
}
